<template>
  <div class="app-container">
    <el-card>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="关键字:">
          <el-input v-model="queryForm.keyword" placeholder="请输入关键字" style="width: 128px;" prefix-icon="el-icon-search"
                    size="small"
                    clearable
          />
        </el-form-item>
        <el-form-item label="当前状态:">
          <el-select v-model="queryForm.status" multiple size="small" style="width: 268px;" placeholder="请选择">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人:">
          <el-input v-model="queryForm.handlerUid" placeholder="请输入" style="width: 128px;" prefix-icon="el-icon-search"
                    size="small"
                    clearable
          />
        </el-form-item>
        <el-form-item label="创建人:">
          <el-input v-model="queryForm.creatorUid" placeholder="请输入" style="width: 128px;" prefix-icon="el-icon-search"
                    size="small"
                    clearable
          />
        </el-form-item>
        <el-form-item label="只筛选主工单:">
          <el-switch
            v-model="queryForm.isMainOrder"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="日期范围:">
          <el-date-picker
            v-model="queryForm.dateRange"
            :editable="false"
            style="width: 236px;"
            size="small"
            type="daterange"
            align="right"
            unlink-panels
            value-format="yyyy/MM/dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="fetchData(1)">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="listLoading"
        :data="list"
        element-loading-text="Loading"
        border
        stripe
        highlight-current-row
        :default-sort="{prop: 'created_at', order: 'descending'}"
        @sort-change="sortChange"
      >
        <el-table-column align="center" label="编号" width="64">
          <template v-slot="scope">
            {{ scope.row.tid }}
          </template>
        </el-table-column>
        <el-table-column label="工单名称">
          <template v-slot="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="机构编号" max-width="162">
          <template v-slot="scope">
            {{ scope.row.header_value | getOrgNum }}
          </template>
        </el-table-column>
        <el-table-column label="未处理问题记录" max-width="152">
          <template v-slot="scope">
            {{ scope.row.unfinished_question | getQuestion }}
          </template>
        </el-table-column>
        <el-table-column label="当前状态" align="center" width="92">
          <template v-slot="scope">
            <el-tag :type="scope.row.type | statusFilter">{{ scope.row.type | statusLabel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="当前处理人" align="center" width="100">
          <template v-slot="scope">
            <span>{{ scope.row.handler_info.realname }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" width="100">
          <template v-slot="scope">
            <span>{{ scope.row.creator_info.realname }}</span>
          </template>
        </el-table-column>
        <el-table-column sortable="custom" align="center" prop="created_at" label="创建时间" width="110">
          <template v-slot="scope">
            <i class="el-icon-time" />
            <span>{{ scope.row.created_at.slice(0,10) }}</span>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="操作" align="center" width="120">
          <template v-slot="scope">
            <el-button size="mini" :icon="(scope.row.handler===userInfo.uid)&&(scope.row.type===1)?'el-icon-edit':'el-icon-search'" type="primary" @click="$router.push({path:'/workOrderSys/orderDetail',query:{tid:scope.row.tid}})">{{ (scope.row.handler===userInfo.uid)&&(scope.row.type===1)?'编辑':'查看' }}</el-button>
            <el-button size="mini" icon="el-icon-menu" type="primary"
                       style="margin-top: 4px;margin-left: 0;"
                       @click.native="$router.push(`/workOrderSys/childOrderView/${scope.row.ftid===-1?scope.row.tid:scope.row.ftid}`)"
            >集合
            </el-button>
            <!--            <el-button v-if="scope.row.handler===userInfo.uid&&scope.row.type===1" size="mini" icon="el-icon-copy-document" type="primary" @click="saveTid(scope.row.tid)">流转</el-button>-->
            <!--            <el-button v-if="scope.row.type===3" size="mini" icon="el-icon-circle-check" type="primary" @click="claim(scope.row.tid)">认领</el-button>-->
            <!--            <el-button v-if="scope.row.type===1" size="mini" icon="el-icon-s-check" type="warning" @click="confirmArchive(scope.row.tid)">归档</el-button>-->
            <el-dropdown v-if="scope.row.type===2" trigger="click" style="margin-top: 10px;" size="mini">
              <el-button size="mini" type="success">
                下载<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item icon="el-icon-download" @click.native="download(scope.row.tid,1)">下载excel</el-dropdown-item>
                <el-dropdown-item icon="el-icon-download" @click.native="download(scope.row.tid,2)">查看pdf</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <el-dropdown v-if="scope.row.type!=2" trigger="click" style="margin-top: 4px;" size="mini">
              <el-button size="mini" type="primary">
                操作<i class="el-icon-arrow-down el-icon--right" />
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="scope.row.handler===userInfo.uid&&scope.row.type===1" icon="el-icon-copy-document" type="primary" @click.native="saveTid(scope.row.tid)">流转</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.type===3" icon="el-icon-circle-check" type="primary" @click.native="claim(scope.row.tid)">认领</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.type===1 && scope.row.ftid===-1" icon="el-icon-s-check" type="warning"
                                  @click.native="confirmArchive(scope.row.tid,scope.row.header_value)"
                >归档
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown></template>
        </el-table-column>
      </el-table>
      <el-dialog title="提交新工单" :visible.sync="submitDialogFormVisible">
        <el-form ref="ruleForm" :model="queryUser" status-icon class="demo-ruleForm" style="margin-left: 12px">
          <el-form-item>
            <span>该操作将提交工单进入流转状态，请确认工单是否正确填写。</span>
          </el-form-item>
          <el-form-item label="工单流转至:">
            <el-input v-model="queryUser.keyword" placeholder="请输入姓名或工号" style="width: 200px;"
                      prefix-icon="el-icon-search"
                      size="small"
                      @keyup.enter.native="searchUser(1)"
            />
            <el-button type="primary" icon="el-icon-search" size="small" style="margin-left: 12px" @click="searchUser(1)">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-table
          v-loading="listLoading"
          :data="searchList"
          style="width: 100%"
        >
          <el-table-column
            label="工号"
            prop="uid"
          />
          <el-table-column
            label="姓名"
            prop="username"
          />
          <el-table-column
            align="right"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                @click="handleTo(scope.row.uid)"
              >流转给TA</el-button>
            </template></el-table-column>
        </el-table>
        <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
          <el-pagination
            :page-size="5"
            background
            layout="prev, pager, next"
            :current-page.sync="dialogCurrentPage"
            :total="dialogTotal"
            @current-change="searchUser(dialogCurrentPage)"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="submitDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="subToFreeStore">流转至自由状态</el-button>
        </div>
      </el-dialog>
      <div style="width: 100%;text-align: center;margin:24px 0 0 0;">
        <el-pagination
          :page-size="pageSize"
          background
          layout="prev, pager, next"
          :current-page.sync="currentPage"
          :total="total"
          @current-change="fetchData(currentPage)"
        />
      </div>
    </el-card>
  </div>
</template>

<script>
import {DATE_RANGE_OPTIONS, getQuestion, MAPPER, PAGE_SIZES, STATUS_OPTIONS} from '@/utils/common'
import { archiveOrder, claimFreeOrder, download, getMyRelatedOrder, moveOrder, toFreeStore } from '@/api/table'
import { findUser } from '@/api/user'
import { BASE_URL } from '@/utils/request'
import { Loading } from 'element-ui'

export default {
  name: 'MyRelated',
  filters: {
    statusFilter(type) {
      const mapper = {
        1: '',
        2: 'warning',
        3: 'success'
      }
      return mapper[type]
    },
    statusLabel(type) {
      for (const item of STATUS_OPTIONS) {
        if (item.value === type) return item.label
      }
    },
    getQuestion,
    getOrgNum(json) {
      const data = JSON.parse(json)
      if (data.orgNum) {
        return data.orgNum
      } else {
        return '无'
      }
    }
  },
  data() {
    return {
      orderOrder: 2,
      searchList: [],
      dialogCurrentPage: 1,
      dialogTotal: 0,
      submitDialogFormVisible: false,
      queryUser: {
        keyword: '',
        tid: 0
      },
      statusOptions: STATUS_OPTIONS,
      currentPage: 1,
      pageSize: PAGE_SIZES,
      total: 0,
      queryForm: {
        isMainOrder:false,
        keyword: '',
        status: [],
        handlerUid: '',
        dateRange: null,
        creatorUid: ''
      },
      list: null,
      listLoading: true,
      pickerOptions: DATE_RANGE_OPTIONS
    }
  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo
    }
  },
  created() {
    this.fetchData(1)
  },
  methods: {
    sortChange(column) {
      if (column.order == null) {
        if (this.orderOrder === 2) {
          column.column.order = 'ascending'
          column.order = 'ascending'
          this.orderOrder = 1
        } else {
          this.orderOrder = 2
          column.column.order = 'descending'
          column.order = 'descending'
        }
      } else {
        if (column.order == 'ascending') {
          this.orderOrder = 1
        } else {
          this.orderOrder = 2
        }
      }
      this.fetchData(1)
    },
    claim(tid) {
      claimFreeOrder(tid).then(res => {
        this.$message.success('认领表单成功')
        this.fetchData(1)
      })
    },
    subToFreeStore() {
      toFreeStore(this.queryUser.tid).then(res => {
        this.$message.success('流转成功')
        this.submitDialogFormVisible = false
        this.fetchData(1)
      })
    },
    handleDownload(fileName, path) {
      const url = BASE_URL + path
      // window.location.href = url
      const el = document.createElement('a')
      el.style.display = 'none'
      el.setAttribute('target', '_blank')
      /**
       * download的属性是HTML5新增的属性
       * href属性的地址必须是非跨域的地址，如果引用的是第三方的网站或者说是前后端分离的项目(调用后台的接口)，这时download就会不起作用。
       * 此时，如果是下载浏览器无法解析的文件，例如.exe,.xlsx..那么浏览器会自动下载，但是如果使用浏览器可以解析的文件，比如.txt,.png,.pdf....浏览器就会采取预览模式
       * 所以，对于.txt,.png,.pdf等的预览功能我们就可以直接不设置download属性(前提是后端响应头的Content-Type: application/octet-stream，如果为application/pdf浏览器则会判断文件为 pdf ，自动执行预览的策略)
       */
      fileName && el.setAttribute('download', fileName)
      el.href = url
      console.log(el)
      document.body.appendChild(el)
      el.click()
      document.body.removeChild(el)
    },
    download(tid, type) {
      const loadingInstance = Loading.service({ fullscreen: true, text: '文件生成中，请稍等......' })
      download(tid).then(res => {
        const data = JSON.parse(res.data)
        if (type === 1) {
          this.handleDownload('output.xlsx', data.excel)
        } else {
          this.handleDownload('output.pdf', data.pdf)
        }
        loadingInstance.close()
      }).catch(() => {
        loadingInstance.close()
      })
    },
    saveTid(tid) {
      this.queryUser.tid = tid
      this.submitDialogFormVisible = true
    },
    handleTo(uid) {
      moveOrder(this.queryUser.tid, uid).then(res => {
        this.$message({
          type: 'success',
          message: '流转成功!'
        })
        this.submitDialogFormVisible = false
        this.queryUser.keyword = ''
        this.searchUser(1)
        this.fetchData(1)
      })
    },
    searchUser(page) {
      this.listLoading = true
      findUser(5, page, { name: this.queryUser.keyword }).then(response => {
        this.searchList = response.data.data
        this.dialogTotal = response.data.total
        this.listLoading = false
      })
    },
    getNewDay(dateTemp, days) {
      dateTemp = dateTemp.split('-')
      const nDate = new Date(dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]) // 转换为MM-DD-YYYY格式
      const millSeconds = Math.abs(nDate) + (days * 24 * 60 * 60 * 1000)
      const rDate = new Date(millSeconds)
      const year = rDate.getFullYear()
      let month = rDate.getMonth() + 1
      if (month < 10) month = '0' + month
      let date = rDate.getDate()
      if (date < 10) date = '0' + date
      return (year + '-' + month + '-' + date)
    },
    fetchData(page) {
      const params = {
        name: this.queryForm.keyword,
        handler: this.queryForm.handlerUid,
        creator: this.queryForm.creatorUid,
        order: this.orderOrder
      }
      if (this.queryForm.status.length === 1) {
        params['type'] = this.queryForm.status[0]
      } else if (this.queryForm.status.length >= 1) {
        params['type'] = `(${this.queryForm.status.join()})`
      }
      if (this.queryForm.dateRange) {
        params['begin'] = this.queryForm.dateRange[0].replaceAll('/', '-')
        // 焦晓宇的锅，end日期要加一天
        params['end'] = this.getNewDay(this.queryForm.dateRange[1], 1).replace('/', '-')
      }

      if (this.queryForm.isMainOrder) {
        params['filter'] = 1
      } else {
        params['filter'] = -1
      }

      this.listLoading = true
      getMyRelatedOrder(this.pageSize, page, params).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.currentPage = response.data.page
        this.listLoading = false
      })
    },
    confirmDelete() {
      this.$confirm('此操作将永久删除该工单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    confirmArchive(tid) {
      this.$confirm('此操作将结束该工单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        archiveOrder(tid).then(res => {
          this.$message({
            type: 'success',
            message: '结单成功!'
          })
          this.fetchData(1)
        })
      })
    }
  }
}
</script>
